<template>
    <div style="padding:20px;text-align: left;">
        <el-card class="kb-card" shadow="never">
            <div style="display: flex;justify-content: space-between;align-items: center;text-align: left;">
                <h1 class="title">音色列表</h1>
                <el-button type="primary" @click="drawerVisible = true"><el-icon>
                        <Plus />
                    </el-icon>创建音色</el-button>
            </div>
            <div>
                <el-table :data="voiceList">
                    <template #empty>
                        <el-empty description="暂无音色，快去创建吧~" />
                    </template>
                    <el-table-column prop="id" label="ID" width="80" />
                    <el-table-column prop="alias" label="音色名称" />
                    <el-table-column prop="name" label="音色ID" />
                    <el-table-column prop="create_time" label="创建时间" />
                    <!-- <el-table-column prop="count" label="知识数量" /> -->
                    <el-table-column fixed="right" label="操作" min-width="120">
                        <template #default="scope">
                            <el-button link type="primary" size="small"
                                @click="() => { this.$router.push(`/soundInfo/${scope.row.id}`) }">
                                详情
                            </el-button>
                            <el-button link type="primary" size="small" @click="deleteVoice(scope.row)">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
        </el-card>
    </div>

    <el-drawer v-model="drawerVisible" title="新增音色" :direction="direction" :before-close="handleClose"
        style="text-align: left;">

        <el-form label-position="top">
            <el-form-item label="音色名称">
                <el-input placeholder="请输入音色名称。" v-model="form.alias" />
            </el-form-item>
            <el-form-item label="上传音频文件">
                <el-upload action="#" :auto-upload="false" :on-change="handleChange" :limit="1"
                    accept=".mp3 , .wav, .m4a" name="file">
                    <el-button slot="trigger" type="primary">选取文件</el-button>
                </el-upload>
            </el-form-item>
        </el-form>

        <template #footer>
            <div style="flex: auto">
                <el-button @click="drawerVisible = false">取消</el-button>
                <el-button type="primary" @click="createVoice">确认</el-button>
            </div>
        </template>
    </el-drawer>
</template>

<script>
export default {
    data() {
        return {
            voiceList: [],
            drawerVisible: false,
            direction: 'rtl',
            form: { alias: "" },
        }
    },
    methods: {
        handleChange(file, fileList) {
            this.form.file = file.raw;
        },
        async getVoiceList() {
            try {
                const response = await fetch(`${import.meta.env.VITE_API_URL}/voiceBank/getVoiceList`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({})
                });
                if (response.status === 401) {
                    localStorage.removeItem('access_token');
                    this.$router.push('/login');
                    return;
                }
                if (!response.ok) {
                    throw new Error('Network response was not ok');
                }
                const rs = await response.json();
                console.log("rs:>>:", rs);
                this.voiceList = rs.data;
            } catch (error) {
                console.error('There was a problem with the fetch operation:', error);
            }
        },
        async createVoice() {
            if (!this.form.file) {
                this.$message.warning('请填写所有必填项并上传音频文件');
                return;
            }

            const formData = new FormData();
            formData.append('file', this.form.file);
            formData.append('voice_prefix', this.form.voice_prefix);
            formData.append('user_id', this.form.user_id);
            formData.append('alias', this.form.alias);


            try {
                const response = await fetch(`${import.meta.env.VITE_API_URL}/voiceBank/createVoice`, {
                    method: 'POST',
                    body: formData,
                    headers: {
                        'Authorization': `Bearer ${localStorage.getItem('access_token')}`
                    }
                });

                if (response.status === 401) {
                    localStorage.removeItem('access_token');
                    this.$router.push('/login');
                    return;
                }
                if (response.ok) {
                    const responseData = await response.json();
                    if (responseData.code === 200) {
                        this.voiceList.push(responseData.data);
                        this.drawerVisible = false;
                        this.form = { alias: "", user_id: null, voice_prefix: "", file: null };
                    } else {
                        console.log("创建失败: " + JSON.stringify(responseData));
                    }
                } else {
                    console.log("网络请求失败");
                }
            } catch (error) {
                console.error(error);
                // this.$message.error("发生错误: " + error.message);
            }
        },
        async deleteVoice(row) {
            try {
                const response = await fetch(`${import.meta.env.VITE_API_URL}/voiceBank/deleteVoice`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(row)
                });
                if (response.status === 401) {
                    localStorage.removeItem('access_token');
                    this.$router.push('/login');
                    return;
                }
                if (!response.ok) {
                    throw new Error('Network response was not ok');
                }
                const rs = await response.json();
                console.log("rs:>>:", rs);
                this.getVoiceList();
            } catch (error) {
                console.error('There was a problem with the fetch operation:', error);
            }
        },
        handleClose(done) {
            this.$confirm('确定要关闭吗?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                done();
            }).catch(() => { });
        }
    },
    mounted() {
        this.getVoiceList();
    }
}
</script>

<style></style>
